﻿using System;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;
using YArchitech.Revit;

namespace HYView
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdViewScopeCreation : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string messages, ElementSet elements)
		{
			Document document = cmdData.Application.ActiveUIDocument.Document;
			Selection selection = cmdData.Application.ActiveUIDocument.Selection;
			if (cmdData.Application.ActiveUIDocument.ActiveView.get_Parameter(BuiltInParameter.VIEWER_CROP_REGION).IsReadOnly)
			{
				YJKMessageBox.Show("当前视图不可以设置视图范围。");
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			PickedBox pickedBox;
			try
			{
				pickedBox = selection.PickBox((Autodesk.Revit.UI.Selection.PickBoxStyle)2, "请框选视图范围");
			}
			catch
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			Transform transform = cmdData.Application.ActiveUIDocument.ActiveView.CropBox.Transform;
			XYZ min = cmdData.Application.ActiveUIDocument.ActiveView.CropBox.Min;
			XYZ max = cmdData.Application.ActiveUIDocument.ActiveView.CropBox.Max;
			XYZ xyz = transform.Inverse.OfPoint(pickedBox.Min);
			XYZ xyz2 = transform.Inverse.OfPoint(pickedBox.Max);
			XYZ xyz3 = new XYZ(xyz.X, xyz.Y, min.Z);
			XYZ xyz4 = new XYZ(xyz2.X, xyz2.Y, max.Z);
			double num = (xyz3.X < xyz4.X) ? xyz3.X : xyz4.X;
			double num2 = (xyz3.X < xyz4.X) ? xyz4.X : xyz3.X;
			double num3 = (xyz3.Y < xyz4.Y) ? xyz3.Y : xyz4.Y;
			double num4 = (xyz3.Y < xyz4.Y) ? xyz4.Y : xyz3.Y;
			xyz3 = new XYZ(num, num3, xyz3.Z);
			xyz4 = new XYZ(num2, num4, xyz4.Z);
			BoundingBoxXYZ cropBox = cmdData.Application.ActiveUIDocument.ActiveView.CropBox;
			cropBox.Min = xyz3;
			cropBox.Max = xyz4;
			BoundingBoxXYZ boundingBoxXYZ = new BoundingBoxXYZ();
			boundingBoxXYZ.Min = xyz3;
			boundingBoxXYZ.Max = xyz4;
			boundingBoxXYZ.Enabled = cropBox.Enabled;
			boundingBoxXYZ.Transform = cropBox.Transform;
			Transaction transaction = new Transaction(document, "ViewScopeCreation");
			transaction.Start();
			cmdData.Application.ActiveUIDocument.ActiveView.CropBox = boundingBoxXYZ;
			cmdData.Application.ActiveUIDocument.ActiveView.GetParameter(BuiltInParameter.VIEWER_CROP_REGION_VISIBLE).Set(1);
			cmdData.Application.ActiveUIDocument.ActiveView.GetParameter(BuiltInParameter.VIEWER_CROP_REGION).Set(1);
			transaction.Commit();
			return Autodesk.Revit.UI.Result.Succeeded;
		}
	}
}
